package epam.bookShelf.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import epam.bookShelf.actions.Action;
import epam.bookShelf.actions.ActionsPool;

public class Servlet extends HttpServlet {
	private static final long serialVersionUID = 3135749450924247498L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");

		String uri = request.getRequestURI();

		ActionsPool pool = new ActionsPool();
		Action act = pool.getAction(uri);		
		
		if (act != null) {
			act.run(request, response, getServletContext());
		} else {
			response.sendError(404);
		}		
	}
	
    @Override
    protected void doPost(
    		HttpServletRequest request, 
    		HttpServletResponse response) throws ServletException, IOException 
    {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");

		String uri = request.getRequestURI();

		ActionsPool pool = new ActionsPool();
		Action act = pool.getAction(uri);
		
		if (act != null) {
			act.run(request, response, getServletContext());
		} else {
			response.sendError(404);
		}    	
    }
}
